package com.example.appcontact;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.base.BaseActivity;
import com.example.connect.AsyncTask_Api;
import com.example.connect.AsyncTask_ApiListener;
import com.example.connect.CallApi;
import com.example.connect.ScreenStopper;
import com.example.database.MySQLiteHelper;
import com.example.model.OutLogin;
import com.example.model.OutProfile;
import com.example.model.OutResult;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.SharedPreferencesDB;
import com.example.util.TokenUnableException;
import com.example.util.Util;
import com.example.util.aes256.SecurityUtils;

public class A002Login extends BaseActivity implements OnClickListener,AsyncTask_ApiListener {
	private Button btn_buchmeo, btn_facebook, btn_gmail;
	private EditText et_email, et_password;
	private int type = 0;
	private TextView tv_title, tv_register, tv_login;
	private String key_md5;
	private String key_iv;
	private List<String> array;
	private static final String[] type_email = { "buchmeo", "gmail", "facebook" };
	private Context mContext;
	private String kindOfEmail;
	private OutProfile local;
	private OutProfile server;
	private OutLogin mOutLogin;
	private LinearLayout ln_main,ln_loading;
	private static final int DIALOG_NUMBER = 0;
	private static final int TYPE_LOGIN = 0;
	private static final int TYPE_UPDATE = 1;
	private static final int TYPE_UPDATE_MY_PROFILE = 9;
	private String mNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private void initView() {
		setContentView(R.layout.a002);

		this.mContext = this;

		this.btn_buchmeo = (Button) this
				.findViewById(R.id.a002_btn_login_buchmeo);
		this.btn_facebook = (Button) this
				.findViewById(R.id.a002_btn_login_facebook);
		
		ln_loading  = (LinearLayout)findViewById(R.id.a002_ln_loading);
		ln_main = (LinearLayout) findViewById(R.id.a002_ln_main);
		this.btn_gmail = (Button) this.findViewById(R.id.a002_btn_login_gmail);
		this.et_email = (EditText) this.findViewById(R.id.a002_et_email);
		this.et_password = (EditText) this.findViewById(R.id.a002_et_password);
		this.tv_title = (TextView) this.findViewById(R.id.header_tv_title);
		this.tv_register = (TextView) this.findViewById(R.id.header_tv_back);
		this.tv_login = (TextView) this.findViewById(R.id.header_tv_next);

		this.tv_register.setVisibility(View.VISIBLE);
		this.tv_login.setVisibility(View.VISIBLE);

		this.tv_register.setText(this.getResources().getString(R.string.registry));
		this.tv_login.setText(this.getResources().getString(R.string.login));

		this.tv_register.setOnClickListener(this);
		this.tv_login.setOnClickListener(this);
		this.btn_buchmeo.setOnClickListener(this);
		this.btn_facebook.setOnClickListener(this);
		this.btn_gmail.setOnClickListener(this);

		mNumber = Util.getMyPhoneNumber(mContext);
		changeLayout(0);
		initData();
	}

	private void initData() {
		key_md5 = getResources().getString(R.string.md5_key);
		key_iv = getResources().getString(R.string.iv_key);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.header_tv_back:
			callA001();
			break;
		case R.id.header_tv_next:
			callA003();
			break;
		case R.id.a002_btn_login_buchmeo:
			changeLayout(0);
			break;
		case R.id.a002_btn_login_gmail:
			changeLayout(1);
			break;
		case R.id.a002_btn_login_facebook:
			changeLayout(2);
			break;
		default:
			break;
		}
	}

	private boolean isEmptyAll(String email, String password) {
		if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password))
			return true;
		return false;
	}

	private void callA003() {
		Util.hideSoftKeyboard(mContext, et_email);
		String email, password;
		try {
			email = this.et_email.getText().toString().trim();
			password = this.et_password.getText().toString().trim();
			if (!isEmptyAll(email, password)) {
				if (Util.getNetworkStatus(mContext)) {
					final String emailEncrypt = SecurityUtils.encrypt(email,
							key_iv, key_md5);
					final String passwordEncrypt = SecurityUtils.encrypt(
							password, key_iv, key_md5);
					array = new ArrayList<String>();
					array.add(emailEncrypt);
					array.add(passwordEncrypt);
					array.add(type_email[type]);

					AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
							TYPE_LOGIN, 0, ScreenStopper.STYLE_PROGRESS_PROCESS);
					apiTask.execute();
				} else {
					Util.showDialog(this, R.string.warning, "Network error !",
							R.drawable.exclamation);
				}
			} else {
				Util.showDialog(this, R.string.warning,
						R.string.msg_error_empty_infor, R.drawable.exclamation);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {

		}
	}

	private void changeLayout(int i) {
		switch (i) {
		case 0: // Login BuchMeO
			this.type = 0;
			this.tv_title.setText(this.getResources().getString(
					R.string.login_buchmeo));
			btn_buchmeo.setSelected(true);
			btn_gmail.setSelected(false);
			btn_facebook.setSelected(false);
			break;
		case 1: // Login Gmail
			this.type = 1;
			this.tv_title.setText(this.getResources().getString(
					R.string.login_gmail));
			btn_gmail.setSelected(true);
			btn_buchmeo.setSelected(false);
			btn_facebook.setSelected(false);
			break;
		case 2: // Login Facebook
			btn_facebook.setSelected(true);
			btn_buchmeo.setSelected(false);
			btn_gmail.setSelected(false);
			this.type = 2;
			this.tv_title.setText(this.getResources().getString(
					R.string.login_facebook));
			break;
		}
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		if (serachType == TYPE_LOGIN) {
			OutLogin out = new OutLogin();
			try {
				out = CallApi.getLogin(this, array.get(0),array.get(1),array.get(2));
			} catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			} catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			} catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			} catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		} else if (serachType == TYPE_UPDATE) {
			String token = new SharedPreferencesDB(this).getPrefToken();
			OutResult out = new OutResult();
			try {
				Map<String, String> hashMap = new HashMap<String, String>();
				hashMap.put("properties[phone]", mNumber);
				out = CallApi.getUpdateProfile(this, hashMap, token);
			} catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			} catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			} catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			} catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		}else if (serachType == TYPE_UPDATE_MY_PROFILE){
			OutProfile local  = (OutProfile) apidata;
			String token = new SharedPreferencesDB(this).getPrefToken();
			OutResult out = new OutResult();
			try {
				out = CallApi.getUpdateProfile(this,createHashMapUpdateProfile(local), token);
			} catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			} catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			} catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			} catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		}
		return null;
	}
	private HashMap<String, String> createHashMapUpdateProfile(OutProfile local ) {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		try {
				hashMap.put("properties[first_name]", local.get_first_name());
				hashMap.put("properties[last_name]", local.get_last_name());
				hashMap.put("properties[home_phone]", local.get_home_phone()); // number
				hashMap.put("properties[mobile]", local.get_mobile()); 
				hashMap.put("properties[home_address]", local.get_home_address());
				hashMap.put("properties[gender]",local.get_gender() +""); // 1: none | 0: male | 2 : female
				hashMap.put("properties[birthday]", local.get_birthday());
				hashMap.put("properties[company_name]", local.get_company_name());
				hashMap.put("properties[company_phone]", local.get_company_phone());
				hashMap.put("properties[company_website]", local.get_company_website());
				hashMap.put("properties[company_email]", local.get_company_email());
				hashMap.put("properties[company_address]", local.get_company_address());
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (hashMap != null)
				Log.e("SON 005", "HashMap: " + hashMap.toString());
		}
		return hashMap;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		if (serachType == TYPE_LOGIN) {
			mOutLogin = (OutLogin) apiresult;
			if (mOutLogin != null) {
					Log.e("A002Login", mOutLogin.toString());
					SharedPreferencesDB db = new SharedPreferencesDB(this);
					db.setPrefToken(mOutLogin.getToken());
					db.setPrefEmail(mOutLogin.getProfile().get_email());
					db.setPrefFirstStart(true);
					db.setPrefUpdateId(true);
					db.setPrefId(mOutLogin.getProfile().getId()+"");
				try {
						File f  = this.getDatabasePath(MySQLiteHelper.DATABASE_NAME);
						Log.d("LOGIN" , f.getPath());
					if(f != null && f.exists()){
						Log.d("A002 - FinishApi()", "A002 -  database  No empty!!!");
						openDatabase();
						local = (OutProfile) mDB.getProfile(mOutLogin.getProfile().getId());
						if(local != null){ 
							Log.d("A002 - FinishApi()", "A002 - Have id = " + mOutLogin.getProfile().getId());
							Log.d("A002 - FinishApi()", "A002 - Profile in Database = " + local.toString());
							//co san trong database
							checkKeyByKey(local);
						}else { 
							Log.e("A002 - FinishApi()", "A002 - No have id = " + mOutLogin.getProfile().getId());
							 Intent intent = new Intent(A002Login.this,A006InputProfile.class);
							 intent.putExtra("_data",mOutLogin.getProfile());
							 startActivityForResult(intent, 8);
						}
					}else{ // database empty
						Log.e("A002 - FinishApi()", "A002 - Empty database !!!");
						    Intent intent = new Intent(A002Login.this,A006InputProfile.class);
						    intent.putExtra("_data",mOutLogin.getProfile());
							startActivityForResult(intent, 8);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
	             
				
			}
		} else if (serachType == TYPE_UPDATE_MY_PROFILE) {
			OutResult out = (OutResult) apiresult;
			  if ( out != null && out.getStatus()){
				  Intent intent = new Intent(A002Login.this,A003Contact.class);
				 startActivityForResult(intent, 1);
			 }
		}
	}
    private void checkKeyByKey(final OutProfile local){
    	server  = mOutLogin.getProfile();
    	if(local != null && server != null){ // neu trong database co user nay
    		int t  = local.compareTo(server);
    		if(t == 0){ // hai cai nay bang nhau
    			Intent intent = new Intent(A002Login.this,A003Contact.class);
				startActivityForResult(intent, 1);
    		}else { // hai cai nay co 1 thuoc tinh nao do khac nhau
    			//hoi nguoi dung co muon update thong tin khong?
    			Util.showDialog(mContext, R.string.update, R.string.msg_update,
    					R.string.ok, R.string.cancel,
    					new DialogInterface.OnClickListener() {
    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							if (Util.getNetworkStatus(A002Login.this)) {
    								AsyncTask_Api apiTask = new AsyncTask_Api(A002Login.this, A002Login.this,
    										TYPE_UPDATE_MY_PROFILE, local,
    										ScreenStopper.STYLE_PROGRESS_PROCESS);
    								apiTask.execute();
    							} else {
    								Util.showDialog(A002Login.this, R.string.warning,
    										R.string.network_not_available, R.drawable.exclamation);
    							}
    						}
    					}, new DialogInterface.OnClickListener() {

    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							SharedPreferencesDB db = new SharedPreferencesDB(A002Login.this);
    							db.setPrefUpdateId(false);
    							Intent intent = new Intent(A002Login.this,A003Contact.class);
    							startActivityForResult(intent, 1);
    						}
    					});
    		}
    	}else{ // neu database khong co user nay 
    		openDatabase();
			mDB.createProfile(mOutLogin.getProfile());
			Intent intent = new Intent(A002Login.this,A003Contact.class);
				startActivityForResult(intent, 1);
    	}
    	
    }
	private void callA001() {
		Intent i = new Intent(this, A001NewUser.class);
		this.startActivityForResult(i, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 0) {
			if (data != null) {
				String email = data.getStringExtra("username");
				String pass = data.getStringExtra("password");
				if (email != null && pass != null) {
					et_email.setText(email);
					et_password.setText("");
				}

			}
		} else if (requestCode == 1) {
			ln_loading.setVisibility(View.GONE);
			ln_main.setVisibility(View.VISIBLE);
			et_email.setFocusable(true);
			et_email.setText("");
			et_password.setText("");
		} else if(requestCode  == 8){
			ln_loading.setVisibility(View.VISIBLE);
			ln_main.setVisibility(View.GONE);
			 Log.d("TAG", "BackTologin :" );
			  openDatabase();
			  OutProfile local = (OutProfile) mDB.getProfile(mOutLogin.getProfile().getId());
			   checkKeyByKey(local);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	public void tokenExpride() {
		// TODO Auto-generated method stub

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_NUMBER:
			CharSequence[] array = { "Red", "Blue", "Yellow" };
			return new AlertDialog.Builder(mContext)
					.setTitle(R.string.select_gender)
					.setSingleChoiceItems(array, -1,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							})
					.setPositiveButton(R.string.update,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							}).create();
		default:
			return null;
		}
	}

	private void getUpdateProfile() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this, TYPE_UPDATE,
					0, ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}
}
